﻿using AutoMapper;
using B.S.BaseData.Domain.Entities;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.BaseData.Write.API.Command.RoleCommand;
using MediatR;

namespace B.S.BaseData.Write.API.CommandHandler.RoleHandler
{
    public class UpdateRoleHandler : IRequestHandler<UpdateRoleCommand, APIResult<object>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly IMapper mapper;

        public UpdateRoleHandler(IBaseRepository<Role> roleRep,IMapper mapper)
        {
            this.roleRep = roleRep;
            this.mapper = mapper;
        }
        public async Task<APIResult<object>> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            var role = roleRep.GetAll().Where(x=>x.RoleName==request.RoleName);
            if (role.Count()>0)
            {
                result.Code = APIEnum.Failed;
                result.Msg = "角色名称有重复,不能修改";
                return await Task.FromResult(result);
            }
            var model=mapper.Map<Role>(request);
            model.UpdateUser = "李四";
            model.UpdateTime=DateTime.Now;
            var r = roleRep.Update(model);
            result.Code = APIEnum.Success;
            result.Msg = "修改成功";
            result.Data = r;
            return await Task.FromResult(result);
        }
    }
}
